package com.tgpms.web.element.controller;

import cn.hutool.core.date.DateUtil;
import com.tgpms.auth.security.TokenService;
import com.tgpms.common.Result;
import com.tgpms.exception.*;
import com.tgpms.util.PageInfo;
import com.tgpms.web.element.entity.CommodityMaster;
import com.tgpms.web.element.service.ICommodityMasterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 控制层
 * </p>
 *
 * @author jl
 * @since 2020-07-07
 */
@Api(value = "CommodityMasterController", tags = "D1120物资总清单相关接口")
@RestController
@RequestMapping("/ev/CommodityMaster")
@Slf4j
public class CommodityMasterController {

    @Resource
    private ICommodityMasterService service;
    @Resource
    private TokenService tokenService;

    /**
     * 查询物资总清单信息
     **/
    @ApiOperation(value = "查询物资总清单信息", notes = "查询物资总清单信息", httpMethod = "POST")
    @PostMapping(value = "/selCommodityMasterList")
    public Result selCommodityMasterList(@RequestParam(value = "selparam", required = false) String selparam,
                                         @RequestParam(value = "leftdition", required = false) String leftdition,
                                         @RequestParam(value = "condition", required = false) String condition,
                                         @RequestParam(value = "dataowner") String dataowner,
                                         @RequestParam(value = "pageNo", required = false, defaultValue = "1") String pageNo,
                                         @RequestParam(value = "pageSize", required = false, defaultValue = "10") String pageSize) {
        Result result = new Result();
        PageInfo pageInfo = new PageInfo();
        try {
            pageInfo.setPage(pageNo);
            pageInfo.setSize(pageSize);
            Map<String, String> map = new HashMap<String, String>();
            map.put("selparam", selparam);
            map.put("leftdition", leftdition);
            map.put("condition", condition);
            map.put("dataowner", dataowner);
            pageInfo.setQueryMap(map);
            result = service.selCommodityMasterList(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_QUERY.getExplain());
            throw new QueryException(ExceptionExplain.ERROR_BY_QUERY.getExplain());
        }
        return result;
    }

    @ApiOperation(value = "新增物资总清单接口", notes = "新增物资总清单接口", httpMethod = "POST")
    @PostMapping(value = "/addCommodityMasterInfo")
    public Result addCommodityMasterInfo(@RequestBody CommodityMaster en, HttpServletRequest request) {
        Result result = new Result();
        try {
            String insertName = tokenService.getUserName(request);
            en.setInsertUser(insertName);
            en.setInsertDate(DateUtil.now());
            Map<String, String> map = service.addCommodityMaster(en);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
                result.setData(map.get("data"));
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
            throw new InsertException(ExceptionExplain.ERROR_BY_INSERT.getExplain());
        }
        return result;
    }

    @ApiOperation(value = "修改新增物资总清单接口", notes = "修改新增物资总清单接口", httpMethod = "PUT")
    @PutMapping(value = "/updateCommodityMasterInfo")
    public Result updateCommodityMasterInfo(@RequestBody CommodityMaster en, HttpServletRequest request) {
        Result result = new Result();
        if (en.getQuickCode() == null) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
            return result;
        }
        try {
            //获取token操作人
            en.setModifyUser(tokenService.getUserName(request));
            en.setModifyDate(DateUtil.now());
            Map<String, String> map = service.updateCommodityMaster(en);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
            throw new UpdateException(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
        }
        return result;
    }

    @ApiOperation(value = "删除物资总清单接口", notes = "删除物资总清单接口", httpMethod = "DELETE")
    @DeleteMapping(value = "/deleteCommodityMasterInfo")
    public Result deleteCommodityMasterInfo(@RequestParam(value = "quickCode") Integer quickCode) {
        Result result = new Result();
        if (quickCode == null) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
            return result;
        }
        try {
            Map<String, String> map = service.deleteCommodityMaster(quickCode);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
            throw new DeleteException(ExceptionExplain.ERROR_BY_DELETE.getExplain());
        }
        return result;
    }

    /**
     * Excel批量导入
     */
    @ApiOperation(value = "Excel批量导入物资总清单接口", notes = "Excel批量导入物资总清单接口", httpMethod = "POST")
    @PostMapping("/import")
    public Result batchImport(@RequestParam("file") MultipartFile file, @RequestParam(value = "dataOwner", required = false) String dataOwner, HttpServletRequest request) {
        Result result = new Result();
        String insertName = tokenService.getUserName(request);
        try {
            Map<String, String> map = service.batchImport(file, dataOwner, insertName);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
                result.setData(map.get("data"));
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
            throw new InsertException(ExceptionExplain.ERROR_BY_INSERT.getExplain());
        }
        return result;
    }

    /**
     * 下载Excel模板
     */
    @ApiOperation(value = "下载物资总清单导入模板", notes = "下载物资总清单导入模板", httpMethod = "POST")
    @RequestMapping(value = "/downloadTemp", produces= MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void  downloadTemp(@RequestParam("fileName")String fileName,HttpServletRequest request, HttpServletResponse response) {
        //定义文件名
//        String fileName = "D1120物资总清单导入模板.xlsx";
        try {
            //获取资源文件
            ClassPathResource classPathResource = new ClassPathResource("static/"+fileName);
            //设置响应类型
            response.setCharacterEncoding("UTF-8");
            String type = new MimetypesFileTypeMap().getContentType(fileName);
            response.setHeader("content-Type", type);
            if(Objects.equals(getBrowser(request), "FF")){//如果是火狐,解决火狐中文名乱码问题
                response.setHeader("Content-Disposition",
                        "attachment;fileName=" +new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
            }else{
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }

            //获取资源文件输入流和httpServletResponse的输出流
            try (InputStream inputStream =classPathResource.getInputStream(); ServletOutputStream servletOutputStream = response.getOutputStream()) {
                //把资源文件的二进制流数据copy到response的输出流中
                IOUtils.copy(inputStream, servletOutputStream);
                //清除flush所有的缓冲区中已设置的响应信息至客户端
                response.flushBuffer();
            } catch (Exception e) {
                //错误日志记录
                log.error(e.getMessage());
            }
        } catch (Exception e) {
            //自定义业务异常
            throw new ProjectException("导出模板失败");
        }

    }

    // 判断浏览器种类的方法
    private String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent != null) {
            if (UserAgent.indexOf("msie") >= 0)
                return "IE";
            if (UserAgent.indexOf("firefox") >= 0)
                return "FF";
            if (UserAgent.indexOf("safari") >= 0)
                return "SF";
        }
        return null;
    }

}
